package com.chuguan.poker.controller;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.taglibs.standard.lang.jstl.Logger;
import org.aspectj.weaver.patterns.IfPointcut.IfFalsePointcut;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.stylesheets.StyleSheetList;

import com.chuguan.poker.entity.UserEntity;
import com.chuguan.poker.service.UserService;


@Controller
@RequestMapping("/user")
public class UserController extends HttpServlet{
	
	
	
	@Resource
	private UserService service;
	
	/**
	 * 上传的文件的路径名
	 */
	private static final String UPLOAD_DIRECTORY = "upload";
	
	/**
	 * 
	 */
	private static final Integer MEMORY_THRESHOLD = 1024 * 1024 * 3;
	private static final Integer MAX_FILE_SIZE = 1024 * 1024 * 40;
	private static final Integer MAX_REQUEST_SIZE = 1024 * 1024 * 50;
	

	@ResponseBody
	@RequestMapping(value="/**/dd")
	public ModelAndView upLoad(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
		ModelAndView view = new ModelAndView();
		view.setViewName("index");
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/TomcatTest/UpdateServlet")
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView view = new ModelAndView();
		//判断是否是多媒体文本上传
		if(!ServletFileUpload.isMultipartContent(request)){
			PrintWriter writer = response.getWriter();
			writer.println("Error,enctype");
			writer.flush();
			return view;
		}
		// 配置上传参数
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		// 设置临时内存空间
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		// 文件上传的servlet对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		// 设置文件的最大size,request,和编码格式
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(MAX_REQUEST_SIZE);
		upload.setHeaderEncoding("utf-8");
		
		//服务器的上传目录
		String uploadPath = "F:\\" + UPLOAD_DIRECTORY;		
		//如果没有这个目录就创建一个新的目录
		File uploadDir = new File(uploadPath);
		if(!uploadDir.exists()){
			uploadDir.mkdir();
		}
		 try {
	            // 解析请求的内容提取文件数据
	            @SuppressWarnings("unchecked")
	            List<FileItem> formItems = upload.parseRequest(request);	 
	            if (formItems != null && formItems.size() > 0) {
	                // 迭代表单数据
	                for (FileItem item : formItems) {
	                    // 处理不在表单中的字段
	                    if (!item.isFormField()) {
	                        String fileName = new File(item.getName()).getName();
	                        String filePath = uploadPath + File.separator + fileName;
	                        File storeFile = new File(filePath);
	                        // 在控制台输出文件的上传路径
	                        System.out.println(filePath);
	                        // 保存文件到硬盘
	                        item.write(storeFile);
	                        request.setAttribute("message",
	                            "文件上传成功!");
	                    }
	                }
	            }
	        } catch (Exception ex) {
	            request.setAttribute("message",
	                    "错误信息: " + ex.getMessage());
	        }
		view.setViewName("message");
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/*/chuguan",method=RequestMethod.GET)
	public ModelAndView doFirst(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
		ModelAndView view = new ModelAndView();
		view.setViewName("cal");
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/welcome",method=RequestMethod.POST)
	public ModelAndView doWelcome(HttpServletRequest request, HttpServletResponse reponse,String username,String phone,String password,String age) throws Exception {
		ModelAndView view = new ModelAndView();
		System.out.println(username+" "+phone+" " + password + " " + age);
		view.addObject("name",username);
		view.addObject("password",password);
		view.addObject("phone",phone);
		view.addObject("age",age);
		view.setViewName("welcome");
		return view;
	}
	
	@ResponseBody
	@RequestMapping("/result/{aa}/{username}")
	public UserEntity returnResult(@PathVariable("aa") Integer age, @PathVariable("username") String name ){
		UserEntity user = new UserEntity();
		user.setName(name);
		user.setAge(age);
		return user;
	}
	
	@ResponseBody
	@RequestMapping(value="/register/checkName")
	public Map<String, Boolean> checkTheSameName(String username){
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		Integer number = service.checkTheSameName(username);
		if(number==0){
			map.put("result",false);
		}else{
			map.put("result",true);
		}
		return map;
	}

}
